//
//  LRJFoodViewController.m
//  BreadTravel
//
//  Created by 李润嘉 on 15/1/3.
//  Copyright © 2015年 李润嘉. All rights reserved.
//

#import "LRJFoodViewController.h"
#import "LRJFoodModel.h"
#import "LRJFoodTableViewCell.h"
#import "LRJFoodDetailViewController.h"

@interface LRJFoodViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating,UISearchBarDelegate>
@property (nonatomic, retain)UITableView *myFoodTableView;
@property (nonatomic, retain)NSMutableArray *myArray;
@property (nonatomic, retain)MBProgressHUD *hud;
@property (nonatomic, retain)NSMutableArray *searchArray;
@property (nonatomic, retain)UISearchBar *mySearchBar;
@property (nonatomic, retain)UISearchController *searchController;
@property (nonatomic, retain)UISearchController *searchDC;
@property (nonatomic, retain)NSString *searchStr;


@end

@implementation LRJFoodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImage *leftImage = [UIImage imageNamed:@"btn_nav_back@2x.png"];
    leftImage = [leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStyleDone target:self action:@selector(leftButtonAction:)];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 15, 50, 20)];
    titleLabel.text = @"美食";
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    
    //创建tableView
    [self myTableView];
    
    //注册cell
    [self.myFoodTableView registerClass:[LRJFoodTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    //去掉cell的线
    self.myFoodTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //初始化数组
    self.myArray = [NSMutableArray array];
    self.searchArray = [NSMutableArray array];
    
    
#pragma mark -- 搜索
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    
    //设置点击搜索框时候隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    //    [searchBar sizeToFit]:设置searchBar位置自适应
    [self.searchController.searchBar sizeToFit];
    self.myFoodTableView.tableHeaderView = self.searchController.searchBar;

    
  //菊花转起来
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.hud show:YES];
    self.hud.labelText = @"正在加载中...";
    [self.view addSubview:self.hud];
    

    //请求网络数据
    [self getAFNetWorkingData];
    
    
      
    
}

//返回
-(void)leftButtonAction:(UIBarButtonItem *)bar{
    
   [self dismissViewControllerAnimated:YES completion:^{
       
       
   }];
    
}
#pragma mark -- 请求网络数据
- (void)getAFNetWorkingData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/list?app_installtime=1447342345.466938&app_versions=5.0.1&category=11&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&os_versions=9.1&page=0&pagesize=20&screensize=640&track_device_info=iPhone6%%2C2&track_deviceid=E11A2F27-9015-4F3F-BE59-C2722D617262&v=8"];
    [AFNetworkTool getUrl:urlStr body:nil result:HXJSON headerFile:nil success:^(id result) {
        [self.myArray removeAllObjects];
        NSMutableDictionary *firstDic = result;
        NSMutableDictionary *dataDic = [firstDic objectForKey:@"data"];
        NSMutableArray *topicArr = [dataDic objectForKey:@"topic"];
        for (NSMutableDictionary *dic in topicArr) {
            LRJFoodModel *foodModel = [[LRJFoodModel alloc] init];
            [foodModel setValuesForKeysWithDictionary:dic];
            [self.myArray addObject:foodModel];
            NSLog(@"-=-=-=-=-%@", self.myArray);
            
        }
        [self.myFoodTableView reloadData];
        [self.hud hide:YES];
    } failure:^(NSError *error) {
        
        NSLog(@"error = %@", error);
        
    } ];
    
    
    

}
#pragma mark -- 创建TableView
- (void)myTableView
{
    self.myFoodTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49) style:UITableViewStylePlain];
    self.myFoodTableView.delegate = self;
    self.myFoodTableView.dataSource = self;
    [self.view addSubview:self.myFoodTableView];
}
#pragma mark -- myTableView必须实现的方法
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (self.searchController.active) {
        return self.searchArray.count;
    }
    else {
        return self.myArray.count;
    }

    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndenifier = @"cell";
    LRJFoodTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndenifier];
   //搜索
    if (self.searchController.active) {
        LRJFoodModel *foodModel = [self.searchArray objectAtIndex:indexPath.row];
        cell.foodModel = foodModel;
#pragma mark -- 关键字高亮实现
        //重写keyWord set方法
        cell.keyWord = self.searchStr;
        self.tabBarController.tabBar.hidden = YES;
        
    }
    else {
        LRJFoodModel *foodModel = [self.myArray objectAtIndex:indexPath.row];
        cell.foodModel = foodModel;
        self.tabBarController.tabBar.hidden = NO;
    }
    

    
    //点击无置灰效果
    cell.selectionStyle = UITableViewCellAccessoryNone;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return WIDTH - 150;
}
#pragma mark -- 点击cell触发方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LRJFoodModel *foodModel = nil;
    
    if (self.searchController.active) {
        
        NSLog(@"选中搜索列表");
        foodModel = [self.searchArray objectAtIndex:indexPath.row];
        
    }
    else {
        
        NSLog(@"选中所有列表");
        foodModel = [self.myArray objectAtIndex:indexPath.row];
        
    }

    LRJFoodDetailViewController *foodDetailVc = [[LRJFoodDetailViewController alloc] init];

    foodDetailVc.modelId = foodModel.modelId;
    [self.navigationController pushViewController:foodDetailVc animated:YES];
}


#pragma mark -- 实现搜索方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    self.searchStr = [self.searchController.searchBar text];
    //将搜索过的移出数组
    [self.searchArray removeAllObjects];
    for (LRJFoodModel *foodModel in self.myArray)
    {
        //rangeOfString:方法是在model.title中搜索是否包含searchText
        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
        //NSNotFound 表示请求操作的某个内容没有发现
    if ([foodModel.title rangeOfString:self.searchStr].location != NSNotFound)
    {
        
         [self.searchArray addObject:foodModel];
       
    }
        
        
}
    
    [self.myFoodTableView reloadData];
}
//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}




//输入文字就触发的方法
//- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
//    
//    NSLog(@"输入框中的内容=====%@",searchText);
//    [self.searchArray removeAllObjects];
//    for (LRJFoodModel *foodModel in self.myArray) {
//        
//        //rangeOfString:方法是在movieName中搜索是否包含searchText
//        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
//        //NSNotFound 表示请求操作的某个内容没有发现
//        if ([foodModel.title rangeOfString:searchText].location != NSNotFound) {
//            
//            [self.searchArray addObject:foodModel];
//        }
//    }
//    
//}






//    //将model定义成属性在下一详情界面可以使用这个model里的属性
//    LRJFeaturesModel *featuresModel = [self.modelArray objectAtIndex:indexPath.row];
//    
//    LRJFeaturesDetailViewController *featuresDVC = [[LRJFeaturesDetailViewController alloc] init];
//    //    NSLog(@"-----%@", featuresModel.name);
//    featuresDVC.featuresModel = featuresModel;
//    [self.travelVC.navigationController pushViewController:featuresDVC animated:YES];
//    
//}
//

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
